const Config = require('../models/config');
const { ApiError } = require('../utils/errorHandler');
const logger = require('../utils/logger');

class ConfigService {
  /**
   * Search configs by term
   * @param {string} searchTerm
   * @param {Object} options
   * @returns {Promise<{configs: Config[], total: number, page: number, limit: number}>}
   */
  async searchConfigs(searchTerm, options = {}) {
    try {
      return await Config.searchConfigs(searchTerm, options);
    } catch (error) {
      logger.error('Error in searchConfigs service:', error);
      throw new ApiError(500, 'Error searching configurations');
    }
  }

  /**
   * Create a new config
   * @param {Object} configData
   * @returns {Promise<Config>}
   */
  async createConfig(configData) {
    try {
      const config = new Config(configData);
      return await config.save();
    } catch (error) {
      logger.error('Error in createConfig service:', error);
      throw new ApiError(400, error.message);
    }
  }

  /**
   * Get config by id
   * @param {string} id
   * @returns {Promise<Config>}
   */
  async getConfigById(id) {
    const config = await Config.findById(id);
    if (!config) {
      throw new ApiError(404, 'Configuration not found');
    }
    return config;
  }

  /**
   * Update config by id
   * @param {string} id
   * @param {Object} updateData
   * @returns {Promise<Config>}
   */
  async updateConfig(id, updateData) {
    try {
      const config = await Config.findByIdAndUpdate(
        id,
        { $set: updateData },
        { new: true, runValidators: true },
      );

      if (!config) {
        throw new ApiError(404, 'Configuration not found');
      }

      return config;
    } catch (error) {
      logger.error('Error in updateConfig service:', error);
      throw new ApiError(400, error.message);
    }
  }

  /**
   * Delete config by id
   * @param {string} id
   * @returns {Promise<void>}
   */
  async deleteConfig(id) {
    const config = await Config.findByIdAndDelete(id);
    if (!config) {
      throw new ApiError(404, 'Configuration not found');
    }
  }

  /**
   * Get configs with pagination and filtering
   * @param {Object} options
   * @returns {Promise<{configs: Config[], total: number, page: number, limit: number}>}
   */
  async getConfigs(options) {
    const {
      page = 1, limit = 10, sortBy = 'createdAt', order = 'desc',
    } = options;
    const skip = (page - 1) * limit;

    try {
      const [configs, total] = await Promise.all([
        Config.find()
          .sort({ [sortBy]: order })
          .skip(skip)
          .limit(limit),
        Config.countDocuments(),
      ]);

      return {
        configs,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
      };
    } catch (error) {
      logger.error('Error in getConfigs service:', error);
      throw new ApiError(500, 'Error retrieving configurations');
    }
  }
}

module.exports = new ConfigService();
